import tornado.httpserver
from tornado import options
from config import port, num, log_path
from forum import creat_app
import asyncio
from tornado.netutil import bind_sockets
import logging

sockets = bind_sockets(port)
tornado.process.fork_processes(num)


class LogFormatter(tornado.log.LogFormatter):
    def __init__(self):
        super(LogFormatter, self).__init__(
            fmt='%(color)s[%(process)d %(asctime)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s]%(end_color)s  %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )


async def post_fork_main():
    tornado.options.options.logging = "error"  # 设置日志登记
    tornado.options.options.log_file_prefix = log_path  # 存储路径
    tornado.options.options.log_rotate_mode = 'time'  # 切割方式：按时间
    tornado.options.options.log_rotate_when = 'H'  # 切割单位：天
    tornado.options.options.log_rotate_interval = 1  # 间隔值：1天
    tornado.options.parse_command_line()
    [i.setFormatter(LogFormatter()) for i in logging.getLogger().handlers]  # 自定义格式化日志， 必须放在 配置解析 后
    app = creat_app()
    server = tornado.httpserver.HTTPServer(app)
    server.add_sockets(sockets)
    await asyncio.Event().wait()


if __name__ == '__main__':
    asyncio.run(post_fork_main())
